package priv.wjh.study.pay.paypal;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

import java.time.LocalDateTime;
import java.util.Base64;

@RequiredArgsConstructor
@Configuration
public class PaypalComponent {

    @Bean
    public static PaypalClient paypalClientForTest(PaypalProperties paypalProperties) {
        WebClient webClient = WebClient.builder()
//                .baseUrl("https://75856cf5-b247-4cf3-acfc-3d3370421a45.mock.pstmn.io")
                .baseUrl(paypalProperties.getBaseUrl())
                .build();
        HttpServiceProxyFactory httpServiceProxyFactory =
                HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient))
                        .build();
        return httpServiceProxyFactory.createClient(PaypalClient.class);
    }

    private static String TOKEN = "";
    private static LocalDateTime EXPERIMENT_DATE;

    private final PaypalClient paypalClient;
    private final PaypalProperties paypalProperties;

    public void initToken(){
        var waitEncode = paypalProperties.getClientId() + ":" + paypalProperties.getClientSecret();
        var authorization = "Basic " + Base64.getEncoder().encodeToString(waitEncode.getBytes());

        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
        parts.add("grant_type", "client_credentials");
        var res = paypalClient.getToken(authorization, parts);
        if (!res.containsKey("access_token") || !res.containsKey("expires_in")){
            throw new RuntimeException("Failed to parse response");
        }
        TOKEN = (String) res.get("access_token");
        EXPERIMENT_DATE = LocalDateTime.now().plusSeconds((Long) res.get("expires_in"));
    }


}
